new Vue({
    el: '#app',
    data: {
        loading: true,
        choiceNames: ['选项1'],
        // 选择题表单
        choiceQuestion: {
            question: '',
            choices: [{
                value: ''
            }],
            answer: [],
            open: false,
            categoryIds: []
        },
        // 填空题表单
        blankQuestion: {
            question: '',
            answers: [''],
            open: false,
            categoryIds: []
        },
        // 判断题表单
        judgeQuestion: {
            question: '',
            // 0对、1错
            answer: '',
            open: false,
            categoryIds: []
        },
        // 解答题表单
        solveQuestion: {
            question: '',
            answer: '',
            open: false,
            categoryIds: []
        },
        // 新增分类表单可见性
        dialogFormVisible: false,
        // 新增分类表单
        categoryForm: {
            name: '',
            open: false
        },
        categories: [],
        // 上一次新增题目的分类
        lastCategoryIds: [],
        curPrefixUrl: prefixUrl + gatewayPrefix.question
    },
    methods: {
        // 点击了新增分类按钮
        addCategoryButton() {
            this.dialogFormVisible = true;
        },
        // 生成ChoiceQuestionAddDTO
        generateChoiceDTO() {
            // 选项
            let choice = this.choiceQuestion.choices[0].value.trim();
            for (let i = 1; i < this.choiceQuestion.choices.length; i++) {
                const value = this.choiceQuestion.choices[i].value.trim();
                console.log("value=" + value);
                choice += (split.default + value);
            }
            // 答案
            let answer = '';
            for (let i = 0; i < this.choiceQuestion.answer.length; i++) {
                answer += (this.choiceQuestion.answer[i]);
            }
            // 是否公开
            let open;
            if (this.choiceQuestion.open) {
                open = openStatus.open;
            } else {
                open = openStatus.notOpen;
            }
            return {
                'question': this.choiceQuestion.question,
                'choice': choice,
                'answer': answer,
                'open': open,
                'categoryIds': this.choiceQuestion.categoryIds,
                'kind': questionKind.choice
            };
        },
        // 生成CategoryAddDTO
        generateCategoryAddDTO() {
            let open;
            if (this.categoryForm.open) {
                open = openStatus.open;
            } else {
                open = openStatus.notOpen;
            }
            return {
                'name': this.categoryForm.name,
                'open': open
            };
        },
        // 新增分类具体操作（点击了对话框中的确定）
        addCategory() {
            // showAlert(this, this.categoryForm);
            const categoryAddDTO = this.generateCategoryAddDTO();
            const url = this.curPrefixUrl + "/user/categories";
            axios.post(url, categoryAddDTO).then((resp) => {
                const result = resp.data;

                showSuccessMsg(this, "新增成功");
                // 清空表单
                this.categoryForm = {
                    name: '',
                    open: false
                }
                // 刷新分类
                this.getMyCategories();
            }).finally(() => {
                this.loading = false;
                this.dialogFormVisible = false;
            });
        },
        // 新增选择题
        addChoice() {
            if (this.choiceQuestion.question.trim() === '') {
                showAlert(this, "题目内容不能为空");
                return;
            }
            if (this.choiceQuestion.categoryIds.length === 0) {
                showAlert(this, "请至少选择一个分类");
                return;
            }
            if (this.choiceQuestion.choices.length === 1 && this.choiceQuestion.choices[0].value.trim() === '') {
                showAlert(this, "选项内容不能为空");
                return;
            }
            if (this.choiceQuestion.answer.length === 0) {
                showAlert(this, "答案不能为空");
                return;
            }

            let choiceQuestionAddDTO = this.generateChoiceDTO();
            // showAlert(this, choiceQuestionAddDTO);
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions";
            axios.post(url, choiceQuestionAddDTO).then((resp) => {
                const result = resp.data;

                showSuccessMsg(this, "添加成功");
                // 清空表单
                this.lastCategoryIds = this.choiceQuestion.categoryIds;
                this.choiceQuestion = {
                    question: '',
                    choices: [{
                        value: ''
                    }],
                    answer: [],
                    open: false,
                    categoryIds: []
                };
                this.choiceQuestion.categoryIds = this.lastCategoryIds;
                // console.log("lastCategoryIds=" + lastCategoryIds);
                // console.log("this.choiceQuestion.categoryIds=" + this.choiceQuestion.categoryIds);
                this.choiceNames = ['选项1'];
            }).finally(() => {
                this.loading = false;
            });
        },
        // 获取我的所有分类
        getMyCategories() {
            this.loading = true;
            const url = this.curPrefixUrl + "/user/categories";
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.categories = result.data;
            }).finally(() => {
                this.loading = false;
            });
        },
        // 删除选项输入框
        removeChoiceInput(item) {
            let index = this.choiceQuestion.choices.indexOf(item)
            if (index !== -1) {
                this.choiceQuestion.choices.splice(index, 1);
                this.choiceNames.pop();
            }
        },
        // 增加选项输入框
        addChoiceInput() {
            if (this.choiceNames.length >= 10) {
                showAlert(this, '最多只能添加10个选项');
                return;
            }
            this.choiceQuestion.choices.push({
                value: '',
            });
            let index = this.choiceNames.length + 1;
            this.choiceNames.push('选项' + index);
        },
        // 填空题增加答案
        addAnswer() {
            this.blankQuestion.answers.push('');
        },
        // 删除答案输入框
        removeAnswerInput(index) {
            this.blankQuestion.answers.splice(index, 1);
        },
        // 新增填空题
        addBlank() {
            if (this.blankQuestion.question.trim() === '') {
                showAlert(this, "题目内容不能为空");
                return;
            }
            if (this.blankQuestion.categoryIds.length === 0) {
                showAlert(this, "请至少选择一个分类");
                return;
            }
            for (let i = 0; i < this.blankQuestion.answers.length; i++) {
                if (this.blankQuestion.answers[i].trim() === '') {
                    showAlert(this, "答案不能为空");
                    return;
                }
            }

            // showAlert(this, this.blankQuestion);

            const blankQuestionAddDTO = this.genBlankQuestionDTO();
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions";
            axios.post(url, blankQuestionAddDTO).then((resp) => {
                const result = resp.data;

                showSuccessMsg(this, "添加成功");
                // 清空表单
                this.lastCategoryIds = this.blankQuestion.categoryIds;
                this.blankQuestion = {
                    question: '',
                    answers: [''],
                    open: false,
                    categoryIds: []
                };
                this.blankQuestion.categoryIds = this.lastCategoryIds;
            }).finally(() => {
                this.loading = false;
            });
        },
        genBlankQuestionDTO() {
            let open;
            if (this.blankQuestion.open) {
                open = openStatus.open;
            } else {
                open = openStatus.notOpen;
            }
            let answer = this.blankQuestion.answers[0].trim();
            for (let i = 1; i < this.blankQuestion.answers.length; i++) {
                answer += (split.default + this.blankQuestion.answers[i].trim());
            }
            return {
                'question': this.blankQuestion.question,
                'answer': answer,
                'categoryIds': this.blankQuestion.categoryIds,
                'open': open,
                'kind': questionKind.blank
            };
        },
        // 新增判断题
        addJudge() {
            if (this.judgeQuestion.question.trim() === '') {
                showAlert(this, "题目内容不能为空");
                return;
            }
            if (this.judgeQuestion.categoryIds.length === 0) {
                showAlert(this, "请至少选择一个分类");
                return;
            }
            if (this.judgeQuestion.answer === '') {
                showAlert(this, "答案不能为空");
                return;
            }

            // showAlert(this, this.judgeQuestion);

            const judgeQuestionAddDTO = this.genJudgeQuestionDTO();
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions";
            axios.post(url, judgeQuestionAddDTO).then((resp) => {
                const result = resp.data;

                showSuccessMsg(this, "添加成功");
                // 清空表单
                this.lastCategoryIds = this.judgeQuestion.categoryIds;
                this.judgeQuestion = {
                    question: '',
                    // 0对、1错
                    answer: '',
                    open: false,
                    categoryIds: []
                };
                this.judgeQuestion.categoryIds = this.lastCategoryIds;
            }).finally(() => {
                this.loading = false;
            });
        },
        genJudgeQuestionDTO() {
            let open;
            if (this.judgeQuestion.open) {
                open = openStatus.open;
            } else {
                open = openStatus.notOpen;
            }
            return {
                'question': this.judgeQuestion.question,
                'answer': this.judgeQuestion.answer,
                'categoryIds': this.judgeQuestion.categoryIds,
                'open': open,
                'kind': questionKind.judge
            };
        },
        // 新增解答题
        addSolve(){
            if (this.solveQuestion.question.trim() === '') {
                showAlert(this, "题目内容不能为空");
                return;
            }
            if (this.solveQuestion.categoryIds.length === 0) {
                showAlert(this, "请至少选择一个分类");
                return;
            }
            if (this.solveQuestion.answer === '') {
                showAlert(this, "答案不能为空");
                return;
            }

            // showAlert(this, this.solveQuestion);

            const solveQuestionAddDTO = this.genSolveQuestionDTO();
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions";
            axios.post(url, solveQuestionAddDTO).then((resp) => {
                const result = resp.data;

                showSuccessMsg(this, "添加成功");
                // 清空表单
                this.lastCategoryIds = this.solveQuestion.categoryIds;
                this.solveQuestion = {
                    question: '',
                    answer: '',
                    open: false,
                    categoryIds: []
                };
                this.solveQuestion.categoryIds = this.lastCategoryIds;
            }).finally(() => {
                this.loading = false;
            });
        },
        genSolveQuestionDTO() {
            let open;
            if (this.solveQuestion.open) {
                open = openStatus.open;
            } else {
                open = openStatus.notOpen;
            }
            return {
                'question': this.solveQuestion.question,
                'answer': this.solveQuestion.answer,
                'categoryIds': this.solveQuestion.categoryIds,
                'open': open,
                'kind': questionKind.solve
            };
        },
    },
    created() {
        // 查询我的分类
        this.getMyCategories();

        // 保存当前数据到sessionStorage
        // 在页面加载时读取sessionStorage里的状态信息
        let dataString = sessionStorage.getItem(storageKey.addQuestionData);
        let data = JSON.parse(dataString);
        if (data) {
            // 有数据直接获取
            Object.assign(this.$data, data)
        }
        // 在页面刷新时将数据保存到sessionStorage里
        window.addEventListener('beforeunload', () => {
            sessionStorage.setItem(storageKey.addQuestionData, JSON.stringify(this.$data));
        })
    }
});